<?php
/*
This file is part of RhizomeCV.
Copyright ©2010 University of Reading (Dr. Karsten Øster Lundqvist <k.o.lundqvist@reading.ac.uk>), 
King's College (Margarita Perez Garcia <contact@margaperez.com>) 
and EIfLE (Marc Van Coillie <marc.van.coillie@eife-l.org>). 

RhizomeCV is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

RhizomeCV is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

RhizomeCV is extended from KiteCV.
Copyright ©2006 Les Developpements Durables <contact@ldd.fr> and
Sébastien Ducoulombier <seb@ldd.fr>.
*/

include_once 'KiteCVDir.php';

class KiteCVPlugin {
	// This class implements the KiteCV plugin functionnalities and screen generation
	// The code is common to Wordpress, DotClear, Elgg ...
	var $dir;
	var $htReqsURL;
	var $exportURL;
	var $exportURL2;
	var $platform;
	var $languageCode;
	var $file;
	var $errorMessage;
	var $noticeMessage;
	var $userId;
	function KiteCVPlugin($dir, $htReqsURL, $exportURL = '', $exportURL2 = '',$platform = 'wordpress') {
		$this->dir = $dir;
		$this->htReqsURL = $htReqsURL;       // HTML requisites base dir for js and icons
		$this->exportURL = $exportURL;
		$this->exportURL2 = $exportURL2;
		$this->platform = $platform;
		$this->languageCode = null;
		$this->userId = null;
		$this->file = null;
		$this->errorMessage = FALSE;
		$this->noticeMessage = FALSE;
	}
	function setLanguageCode($languageCode) {
		$this->languageCode = $languageCode;

		if($this->dir != null)
		{
			$this->dir->setSelectedLanguage($this->userId, $this->languageCode);
		}

		$po_file = dirname(__FILE__).'/../locales/'.$this->languageCode.'/main.po';
		$GLOBALS['_kcv_l10n'] = array();
		$tmp = getPoFile($po_file);
		$GLOBALS['_kcv_l10n'] = array_merge($GLOBALS['_kcv_l10n'],$tmp);
	}
	function setUserId($userId) {
		$this->userId = wp_get_current_user()->ID.$userId;
		$this->dir->setSelectedMaster($userId);

		return $this->userId;
	}

	//For use at a stage before wp has found user info. 
	//$userId *must* have both user and master info e.g. 1test for user = 1 , master = test
	function setUserIdFromExport($userId) {
		$this->userId = $userId;

		return $this->userId;
	}

	function isUser($id)
	{
		if($this->userId == wp_get_current_user()->ID.$id)
		{
			return true;
		}
		
		return false;
	}

	function openFile() {
		$this->file = $this->dir->getFile($this->languageCode, $this->userId);
	}
	function getHeaderHTML() {
		return
		'<style type="text/css">'.
		'@import "'.$this->htReqsURL.'/styles/KiteCV_'.$this->platform.'.css";'.
		'</style>'."\n".
		'<link rel="stylesheet" type="text/css" media="all"'.
		' href="'.$this->htReqsURL.'/js/jscalendar-1.0/calendar-win2k-cold-1.css"'.
		' title="win2k-cold-1"/>'."\n".
		'<script type="text/javascript" src="'.$this->htReqsURL.'/js/jscalendar-1.0/calendar.js"></script>'."\n".
		'<script type="text/javascript" src="'.$this->htReqsURL.'/js/jscalendar-1.0/lang/calendar-en.js"></script>'."\n".
		'<script type="text/javascript" src="'.$this->htReqsURL.'/js/jscalendar-1.0/calendar-setup.js"></script>'."\n".
		'<script type="text/javascript" src="'.$this->htReqsURL.'/js/kitecv.js"></script>'."\n".
		'<script type="text/javascript" src="'.$this->htReqsURL.'/js/common.js"></script>'."\n".
		'<script type="text/javascript" src="'.$this->htReqsURL.'/js/multi-part-page.js"></script>'."\n";
	}
	function doActions() {
		// triggers requested or required actions.
		// Returns TRUE on success, FALSE on error
		// Sets $this->noticeMessage.
		$old_level = error_reporting(E_ALL);
		$missingModules = array();
		if (version_compare(phpversion(), '5') == -1) { // PHP4
			if (!function_exists('domxml_open_file')) {
				$missingModules[] = 'DOM XML';
			}
			if (!function_exists('xslt_create')) {
				$missingModules[] = 'XSLT';
			}
			if (!class_exists('ZipArchive')) {
				$missingModules[] = 'Zip';
			}
		} else { // PHP5
			/* if (!class_exists('ZipArchive')) {
				$missingModules[] = 'Zip';
			} */
			if (!class_exists('XSLTProcessor')) {
				$missingModules[] = 'XSL';
			}
		}
		if (!empty($missingModules)) {
			$this->noticeMessage = 
				'The <strong>KiteCV</strong> plugin requires either<ul><li>PHP5 with modules XSL (required) and Zip (for OpenDocument export), or</li><li>PHP4 with modules DOMXML, XSLT and Zip.</li></ul>Your PHP version is <strong>'.phpversion().'</strong>.';
			foreach ($missingModules as $module) {
				$this->noticeMessage .=
				"<br/>Missing module : <strong>$module</strong>";
			}
			return;
		}
		if (!is_writable($this->dir->path)) {
			$this->errorMessage = 'Directory <em>'.$this->dir->path.'</em> is not writable'.
			' (that is where the KiteCV plugin stores its data).';
			return;
		}
		if (array_key_exists('KiteCVAction', $_POST)) {
			$ok = FALSE;
			switch ($_POST['KiteCVAction']) {
			case 'createCV':
				if ($this->file->create($this->languageCode))
				$this->noticeMessage = KiteCVTranslate('The CV was created.');
				else
				$this->errorMessage = $this->file->getErrorMessage();
				break;
			case 'deleteCV':
				if ($this->file->delete()) {
					$this->noticeMessage = KiteCVTranslate('The CV was deleted.');
					
					$languageList = $this->dir->getEnabledLanguageList($this->userId);
					
					if(count($languageList) == 0) {
						$this->dir->removeMaster($this->userId);
						$masterList = $this->dir->getMasterList();
					
						if(count($masterList) > 0) {
							$this->setUserId($masterList[0]);
						}
						else {
							$this->setUserId("");
						}
					}
					else {
						$this->dir->setSelectedLanguage($this->userId, $languageList[0]);
					}
					
					$lang = $this->dir->getSelectedLanguage($this->userId);
					$this->setLanguageCode($lang);
					
					$this->file = $this->dir->getFile($this->languageCode, $this->userId);
				} 
				else
					$this->errorMessage = $this->file->getErrorMessage();
				break;
			case 'modifyCV':
				if ($this->file->modify()) {
					// This is occuring very often, let's not notify it
					// $this->noticeMessage = 'The CV was modified.';
					if (array_key_exists('photoFile', $_FILES)) {
						if ($this->uploadPhoto())
						$this->noticeMessage = KiteCVTranslate('The photo was uploaded');
						else
						$this->errorMessage = $this->getErrorMessage();
					}
				} else
				$this->errorMessage = $this->file->getErrorMessage();
				break;
			case 'uploadCV':
				if ($this->upload())
				$this->noticeMessage = KiteCVTranslate('The CV was uploaded.');
				else
				$this->errorMessage = $this->getErrorMessage();
				break;
				
			case 'changeMaster':
				if(array_key_exists('KiteCV_masterCode', $_POST)) {
					$KiteCV_masterCode = $_POST['KiteCV_masterCode'];
					
					if(isset($KiteCV_masterCode))
					{
						if(strstr($KiteCV_masterCode, "-") != FALSE)
						{
							$this->errorMessage = "Master name must not include the character '-'";
							break;
						}
					}
					else
					{
						//TODO take care of this proper!
						$this->errorMessage = "Master name should be set.";
						break;
					}
					
					
					$this->setUserId($KiteCV_masterCode);
					
					$lang = $this->dir->getSelectedLanguage($this->userId);
					$this->setLanguageCode($lang);
					
					$this->openfile();
					
					if ($this->file->create($this->languageCode))
					$this->noticeMessage = KiteCVTranslate('The master changed.');
					else
					$this->errorMessage = $this->file->getErrorMessage();
				}	
				break;
			case 'newMaster':
				if(array_key_exists('KiteCV_newMasterAction', $_POST)) {
					$KiteCV_newMasterAction = $_POST['KiteCV_newMasterAction'];
					
					if(strstr($KiteCV_newMasterAction, "-") != FALSE)
					{
						$this->errorMessage = "Master name must not include the character '-'";
						break;
					}
					
					$this->setUserId($KiteCV_newMasterAction);
					
					$lang = $this->dir->getSelectedLanguage($this->userId);
					$this->setLanguageCode($lang);
					
					$this->openfile();
					
					if ($this->file->create($this->languageCode))
					$this->noticeMessage = KiteCVTranslate('The master was created.');
					else
					$this->errorMessage = $this->file->getErrorMessage();
				}	
				break;	
			default:
				$this->errorMessage = 'Unexpected action: '.$_POST['KiteCVAction'];
				break;
			}
		}
		error_reporting($old_level);
	}
	function getErrorMessage() {
		// returns an error message string if any, or FALSE.
		return $this->errorMessage;
	}
	function getNoticeMessage() {
		// returns a notice message string if any, or FALSE.
		return $this->noticeMessage;
	}
	
	function getManagementDiv() {
		$old_level = error_reporting(E_ALL);
		$r = 
			'<div class="wrap">'."\n".
			'<div id="icon-tools" class="icon32"><br/></div>';
			
		if (count($this->dir->getMasterList()) > 0 and $this->file->exists()) {
			$r .= '<h2>CV: Import / Export</h2>'; //TODO language
		}
		else {
			$r .= '<h2>CV: make a master</h2>'; //TODO language
		}
		if (count($this->dir->getMasterList()) > 0) {
			$r .= $this->getMenu();
		} 
		else {
			$r .= '<div id="KiteCV_intro"'."\n";
			$r .= '(Must have one before Importing/Exporting)';
			$r .= $this->getHelp();
			
			$r .= '<div class="clear"></div>';
			$r .= '</div><!-- KiteCV_intro -->'."\n";
			$r .= $this->getMasterSelectorDiv();
		}
		$r .= '<div class="clear"></div>';
		$r .= '</div><!-- wrap -->'."\n";
		error_reporting($old_level);
		return $r;
	}
	
	function getHelp() {
		return KiteCVTranslate(
			'<h3>Welcome to your Europass CV editor.</h3>
<p>The Europass CV Editor allows you to create your own CV using the European Union official format, to customize it according to your presentation needs, publish it online and export it in PDF, ODT, and even HR-XML.</p>
<p></p>
<p>There are 3 simple steps to create your CV:</p>
<ol>
	<li>Store all your personal and professional information in your master CV. The master CV is your personal vault for information, from which you can created other views of your CV!</li>
	<li>Compose views. Views allow you to build a presentation of your CV by selecting the data you want to show and customizing its display.</li>
	<li>Export the CV views as pages of your blog, or as an independent files in different formats like <a href="http://www.adobe.com/products/reader/" target="_blank">PDF</a>, <a href="http://en.wikipedia.org/wiki/Microsoft_Word" target="_blank">DOC</a>, <a href="http://en.wikipedia.org/wiki/OpenDocument" target="_blank">ODT</a>, <a href="http://en.wikipedia.org/wiki/XHTML" target="_blank">XHTML</a> and <a href="http://www.hr-xml.org/hr-xml/wms/hr-xml-1-org/index.php?language=2" target="_blank">HRXML</a>.</li>
</ol>
<br/>
<p>To start, create a master CV from Edit CV.</p>');
	}
	
	function getEditorDiv() {
		$old_level = error_reporting(E_ALL);
		$r = 
			'<div class="wrap">'."\n".
			'<div id="icon-tools" class="icon32"><br/></div>';
		
		if (count($this->dir->getMasterList()) > 0 and $this->file->exists()) {
			$r .= $this->getMasterSelectorHeading();//'<h2>EuropassCV:'.$this->dir->getSelectedMaster().'</h2>'; //TODO language
			$r .= $this->getCVEditorDiv();
		}
		else {
			$r .= $this->getMasterSelectorHeading();
			$r .= '<div id="KiteCV_intro"'."\n";
			$r .= $this->getHelp();			
			$r .= '<div class="clear"></div>';
			$r .= '</div><!-- KiteCV_intro -->'."\n";
		}
		$r .= '<div class="clear"></div>';
		$r .= '</div><!-- wrap -->'."\n";

		error_reporting($old_level);
		return $r;
	}
	
	function getXsltArguments(&$xsltFileName) {
		
		$arguments = 'languageCode='.$this->languageCode; // minimal argument is the currently selected languageCode
		if (array_key_exists('KiteCVXsltName', $_POST) && !empty($_POST['KiteCVXsltName'])) {
			// A right-pane form name was specified.
			$KiteCVXsltName = $_POST['KiteCVXsltName'];
			// Split the actual XSLT file name from its arguments :
			$elements = explode(' ', $KiteCVXsltName);
			$xsltFileName = array_shift($elements);
			if (count($elements) > 0) {
				$arguments .= ' '.implode(' ', $elements);
			}
		}
		
		return $arguments;
	}

	function getMenu() {
		global $core;
		
		$r = 
			'<table class="form-table">'.
			'<tbody>';
		
		//TODO remove commenting to get language - language not really made yet
		//$r .= $this->getCVSelectorDiv();
		//$r .= $this->getCVCreatorDiv();
		
		$r .= $this->getCVUploaderDiv();
		
		$r .=
			'</tbody>'.
			'</table>';
		return $r;
	}
	function getCVEditorDiv() {
		global $core;
		// This function gets called when there is a language code and a valid file exists.
		$xsltFileName = 'hrxml2xhtml_form.xsl'; // default form is the master CV form
		$arguments = $this->getXsltArguments($xsltFileName); 
		return
		'<div id="KiteCV_editorDiv">'."\n".
		'<form id="modifyForm" action="#" method="post" enctype="multipart/form-data">'."\n".
		(is_callable(array($core, 'formNonce')) ? $core->formNonce() : '').
		'<input type="hidden" name="MAX_FILE_SIZE" value="1000000"/>'.
		'<input type="hidden" name="KiteCVXsltName"'.
		' value="'.$xsltFileName.' '.$arguments.'"/>'."\n".
		'<input type="hidden" name="KiteCVAction" value="modifyCV" />'."\n".
		'<input type="hidden" name="delete" />'."\n".
		'<div id="KiteCV_formDiv">'."\n".
		str_replace(
		'_htReqsURL_',
		$this->htReqsURL,
		preg_replace(
		'/_exportURL_\?position=([^&]+)&amp;format=([a-z]+)/',
		sprintf($this->exportURL, $this->userId, $this->languageCode, '$2', '$1'),
		$this->file->generateView("$xsltFileName $arguments", true)
		)
		)."\n".
		'<div class="clear"></div>'.
		'</div><!-- KiteCV_formDiv -->'."\n".
		'<div id="KiteCV_treeDiv">'."\n".
		str_replace(
		'_htReqsURL_',
		$this->htReqsURL,
		preg_replace(
		'/_exportURL_\?position=([^&]+)&amp;format=([a-z]+)/',
		sprintf($this->exportURL, $this->userId, $this->languageCode, '$2', '$1'),
		$this->file->generateView("hrxml2xhtml_mainform.xsl $arguments", true)
		)
		).
		'<br/>'.
		'<div id="EuropassCV_Header">'.
		'<a href="http://europass.cedefop.europa.eu/"'.
		'target="_blank" title="Europass web-site">'.
		'<img src="'.
		$this->htReqsURL.
		'/icons/europass.png" />'.
		'</a>'.
		'</div>'.
		'</div><!-- KiteCV_treeDiv -->'."\n".//To here
		'</form>'."\n".
		'<script type="text/javascript">'."\n".
		'kiteCVOnLoad();'."\n".
		'</script>'."\n".
		'<div class="clear"></div>'.
		'</div><!-- KiteCV_editorDiv -->'."\n";
	}

	function getMasterSelectorHeading() {
		global $core;

		$masters = $this->dir->getMasterList();

		$r = '<h2>CV ';
			
		if(count($masters) > 0) {
			$r .=
				'<form action="#" method="post" class="nav-tab nav-tab-active">'.
				(is_callable(array($core, 'formNonce')) ? $core->formNonce() : '').
				'<input type="hidden" name="KiteCVAction" value="changeMaster"/>'.
				'<input type="hidden" name="KiteCV_languageCode" value="en"/>'.
				'<select id="masterCode" name="KiteCV_masterCode">';
			foreach($masters as $master) {
				$r .=
					'<option value="'.$master.'"'.($this->isUser($master)?' selected="selected"':'').'>'.($master == "" ? "unnamed" : $master).'</option>';
			
				/*if($this->isUser($master)) {
					
					$r .=
						'<form action="#" method="post" class="nav-tab nav-tab-active">'.
						(is_callable(array($core, 'formNonce')) ? $core->formNonce() : '').
						'<input type="hidden" name="KiteCVAction" value="changeMaster"/>'.
						'<label for="masterchange" onclick="javascript:this.form.submit();">'.
						($master == "" ? "unnamed" : $master).
						'</label>'."\n".
						'<input id="masterchange" type="hidden" name="KiteCV_masterCode" value="'.
						$master.
						'"/>'.
						'<input type="hidden" name="KiteCV_languageCode" value="en"/>'."\n".
						'</form>'."\n";
						
				}
				else {
					$r .=
						'<form action="#" method="post" class="nav-tab">'.
						(is_callable(array($core, 'formNonce')) ? $core->formNonce() : '').
						'<input type="hidden" name="KiteCVAction" value="changeMaster"/>'.
						'<label for="masterchange" onclick="javascript:this.form.submit();">'.
						($master == "" ? "unnamed" : $master).
						'</label>'."\n".
						'<input id="masterchange" type="hidden" name="KiteCV_masterCode" value="'.
						$master.
						'"/>'.
						'<input type="hidden" name="KiteCV_languageCode" value="en"/>'."\n".
						'</form>'."\n";
				}*/
			}
			$r .= 
				'</select>'.
				'<button onclick="javascript:this.form.submit();" type="button" class="button">Change Master</button>'."\n".
				'</form>';
		}
		
		$r .=
			'<form action="#" method="post" class="nav-tab">'.
			'<input type="hidden" name="KiteCVAction" value="newMaster"/>'."\n".
			'<input id="makenewmaster" type="text" name="KiteCV_newMasterAction" class="regular-text"/>'.
			'<button onclick="javascript:this.form.submit();" type="button" class="button">New Master</button>'."\n".
			'<input type="hidden" name="KiteCV_languageCode" value="en"/>'."\n".
			'</form>'."\n";
			
		$r .= '</h2>';
		
			
		return $r;
	}
	
	function getMasterSelectorDiv() {
		global $core;

		$masters = $this->dir->getMasterList();

		$r =
			'<form action="#" method="post">'.
			'<tr valign="top">'.
			'<th scope="row">'.
			'<label for="makenewmaster">'.KiteCVTranslate('New Master:').'</label>'.
			'</th>'.
			'<td>'.
			'<input type="hidden" name="KiteCVAction" value="newMaster"/>'."\n".
			'<input id="makenewmaster" type="text" name="KiteCV_newMasterAction" class="regular-text"/>'.
			'<button onclick="javascript:this.form.submit();" type="button" class="button">New Master</button>'."\n".
			'<input type="hidden" name="KiteCV_languageCode" value="en"/>'."\n".	
			'<span class="description">Create an additional Master CV</span>'. //TODO language
			'</td>'.
			'</tr>'.
			'</form>';
		
		$r .= '<tr valign="top">';
		
		if(count($masters) > 0) {
			$r .= 
				'<form action="#" method="post">'.
				'<th scope="row">'.
				'<label for="selectmaster">'.KiteCVTranslate('Select Master:').'</label>'.
				'</th>'.
				(is_callable(array($core, 'formNonce')) ? $core->formNonce() : '').
				'<input type="hidden" name="KiteCVAction" value="changeMaster"/>'."\n".
				'<td>'.
				'<select id="selectmaster" class="KiteCV_languageSelect" name="KiteCV_masterCode" onChange="javascript:this.form.submit();">';
			foreach($masters as $master) {
				$r .=
					'<option'.
					' value="'.$master.'"'.
					($this->isUser($master) ? ' selected="1"' : '').
					'>'.
					($master == "" ? "unnamed" : $master).
					'</option>'."\n";				
			}
			$r .=
				'</select>'."\n".
				'<span class="description">Select a Master CV already present in the system</span>'. //TODO language
				'</td>'.
				'<input type="hidden" name="KiteCV_languageCode" value="en"/>'."\n".
				'</form>'."\n";
		}
		
		$r .= '</tr>';
		
		return $r;
	}

	function getCVSelectorDiv() {
		global $core;
		include "languages.php";
		$enabledLanguages = $this->dir->getEnabledLanguageList($this->userId);
		$r =  '';
		if (count($enabledLanguages) > 0) {
			$r .= 
				'<form action="#" method="post">'."\n".
				'<tr valign="top">'.
				(is_callable(array($core, 'formNonce')) ? $core->formNonce() : '').
				'<th scope="row">'.
				'<label for="cvselect">'.KiteCVTranslate('Select:').'</label>'.
				'</th>'.
				'<td>'.
				'<select id="cvselect" name="KiteCV_languageCode" onChange="javascript:this.form.submit();"'.
				' class="KiteCV_languageSelect"'.
				' style="background-image: url('. $this->htReqsURL.'/icons/flags/'.$this->languageCode.'.png);">';
			foreach ($enabledLanguages as $lang)
				$r .=
					'<option'.
					' value="'.$lang.'"'.
					' style="background-image: url('. $this->htReqsURL.'/icons/flags/'.$lang.'.png);"'.
					($this->languageCode == $lang ? ' selected="1"' : '').
					'>'.
					KiteCVTranslate($availableLanguageList[$lang]).
					'</option>'."\n";
			$r .=
				'</select>'."\n".
				'<span class="description">Select a language</span>'. //TODO language
				'</td>'.
				'</tr>'.
				'</form>'."\n";
		}

		return $r;
	}
	function getCVCreatorDiv() {
		global $core;
		include "languages.php";
		$enabledLanguages = $this->dir->getEnabledLanguageList($this->userId);
		$remainingLanguages = array_diff(
		array_keys($availableLanguageList),
		$enabledLanguages
		);
		$r = '';
		if (count($remainingLanguages) > 0) {
			$r .=
				'<form action="#" method="post">'."\n".
				'<tr valign="top">'.
				(is_callable(array($core, 'formNonce')) ? $core->formNonce() : '').
				'<th scope="row">'.
				'<input type="hidden" name="KiteCVAction" value="createCV"/>'."\n".
				'<label for="createnewcv">'.KiteCVTranslate('Create:').'</label>'."\n".
				'</th>'.
				'<td>'.
				'<select id="createnewcv" class="KiteCV_languageSelect" name="KiteCV_languageCode" onChange="javascript:this.form.submit();">'.
				'<option> </option>';
			foreach ($remainingLanguages as $lang)
				$r .=
					'<option'.
					' value="'.$lang.'" '.
					' style="background-image: url('. $this->htReqsURL.'/icons/flags/'.$lang.'.png);"'.
					'>'.
					KiteCVTranslate($availableLanguageList[$lang]).
					'</option>'."\n";
			$r .=
				'</select>'."\n".
				'<span class="description">Create a new language for your CV</span>'. //TODO language
				'</td>'.
				'</tr>'.
				'</form>'."\n";
		}
		
		return $r;
	}
	function getCVUploaderDiv() {
		global $core;
		$r =
			'<form action="#" method="post" enctype="multipart/form-data">'.
			'<tr valign="top">'.
			(is_callable(array($core, 'formNonce')) ? $core->formNonce() : '').
			'<th scope="row">'.
			'<input type="hidden" name="KiteCVAction" value="uploadCV"/>'.
			'<input type="hidden" name="MAX_FILE_SIZE" value="1000000"/>'.
			'<label for="uploadcv">'.KiteCVTranslate('Upload:').'</label>'.
			'</th>'.
			'<td>'.
			'<input id="uploadcv" type="file" name="cvFile" onChange="javascript:if(confirm(\'Please confirm:\nyour current CV file of the same language, if any, will be overwritten.\')) this.form.submit();"/>'.
			#'<button type="button" onClick="javascript:if(confirm(\'Please confirm:\nyour current CV file of the same language, if any, will be overwritten.\')) this.form.submit();">'.
			'<span class="description">Upload a CV saved earlier (HR-XML export)</span>'. //TODO language
			'</td>'.
			'</tr>'.
			'</form>';
			
		$masters = $this->dir->getMasterList();
		
		if(sizeof($masters > 0)) {
			$r .=
				'<form action="#" method="post" enctype="multipart/form-data">'.
				'<tr valign="top">'.
				(is_callable(array($core, 'formNonce')) ? $core->formNonce() : '').
				'<th scope="row">'.
				'<input type="hidden" name="KiteCVAction" value="downloadCV"/>'.
				'<input type="hidden" name="MAX_FILE_SIZE" value="1000000"/>'.
				'<label for="uploadcv">'.KiteCVTranslate('Download:').'</label>'.
				'</th>'.
				'<td>';
			
			foreach($masters as $master) {
				$r .=
					'<a href="'.
					sprintf($this->exportURL2,$this->dir->getMasterFilename($this->languageCode, wp_get_current_user()->ID, $master)).
					'">'.
					KiteCVTranslate($master).
					'</a><br>'."\n";
			}
		
			$r .=
				'</td>'.
				'</tr>'.
				'</form>';
		}
			
		return $r;
	}
	function replyWithRawFile() {
		header('Content-type: text/xml');
		readfile($this->file->path);
	}
	function replyWithPhoto() {
		header('Content-type: image/jpeg');
		readfile($this->dir->photoPath($this->userId));
	}
	function replyWithExport($format, $position, $accessCode) {
		if ($format == 'photo') {
			return $this->replyWithPhoto();
		}
		include "formats.php"; # for $availableFormatList
		if ($this->file->checkAccessCode($format, $position, $accessCode)) {
			header('Content-type: '.$availableFormatList[$format]['mime-type']);
			if ($format != 'xhtml') {
				header('Content-Disposition: attachment; filename="cv_'.$this->languageCode.'_'.$position.'.'.$format.'"');
			}
			$html = str_replace(
				'_htReqsURL_',
				$this->htReqsURL,
				preg_replace(
					'/_exportURL_\?position=([^&]+)&amp;format=([a-z]+)/',
					sprintf(str_replace('&', '&amp;', $this->exportURL), $this->userId, $this->languageCode, '$2', '$1'),
					$this->file->generateViewFromFormatAndPosition($format, $position)
				)
			);
			if ($format == 'pdf') {
				
				$document = $html;
				$filetype = 'pdf';
				$locale = ''; // autodetect

				stream_wrapper_restore('http');
				$client = new SoapClient("http://europass.cedefop.europa.eu/instrumentssrv/services/Instruments?wsdl", array('exceptions'=>false, 'trace'=>true));
				
				$response = $client->getDocumentFromCV($document, $filetype, $locale);


				echo $response;

			} elseif ($format == 'doc') {				
				$document = $html;
				$filetype = 'doc';
				$locale = ''; // autodetect

				//stream_wrapper_restore('http');
				$client = new SoapClient("http://europass.cedefop.europa.eu/instrumentssrv/services/Instruments?wsdl", array('exceptions'=>false, 'trace'=>true));
				
				$response = $client->getDocumentFromCV($document, $filetype, $locale);


				echo $response;
			} elseif ($format == 'odt') {				
				$document = $html;
				$filetype = 'sxw';
				$locale = ''; // autodetect

				//stream_wrapper_restore('http');
				$client = new SoapClient("http://europass.cedefop.europa.eu/instrumentssrv/services/Instruments?wsdl", array('exceptions'=>false, 'trace'=>true));
				
				$response = $client->getDocumentFromCV($document, $filetype, $locale);


				echo $response;
			}else {
				echo $html;
			}
		} else {
			header('Content-type: text/html');
			echo $this->getAccessCodeFormPage();
		}
	}
	function getAccessCodeFormPage() {
		global $core;
		$r = '<?xml version="1.0"?>'."\n".
		'<html xmlns="http://www.w3.org/1999/xhtml">'.
		'<head>'.
		'<title>Access code required</title>'.
		'</head>'.
		'<body onLoad="javascript:document.forms[0].elements.accessCode.focus();">'.
		'<form action="'.$_SERVER['REQUEST_URI'].'" method="POST">'.
		(is_callable(array($core, 'formNonce')) ? $core->formNonce() : '').
		'<label for="accessCode">Please type the access code:</label>'.
		'<input type="text" name="accessCode"/>'.
		'<button type="submit" class="button">Send</button>'.
		'</form>'.
		'</body>'.
		'</html>';
		return $r;
	}
	function getXHTMLView($position) {
		return str_replace(
		'_htReqsURL_',
		$this->htReqsURL,
		$this->file->generateView(
		'hrxml2xhtml_export.xsl position='.$position
		)
		);
	}
	function upload() {
		$tmp_name = $_FILES['cvFile']['tmp_name'];
		if (is_uploaded_file($tmp_name)) {
			if (version_compare(phpversion(), '5') == -1) { // PHP4
				$dom = domxml_open_file($tmp_name);
			} else { // PHP5
				$dom = new DOMDocument();
				$dom->load($tmp_name);
			}
			if ($dom) {
				if (version_compare(phpversion(), '5') == -1) { // PHP4
					$xpathContext = xpath_new_context($dom);
					xpath_register_ns($xpathContext, hr_ns_prefix, hr_ns_url);
					$xpathResult = $xpathContext->xpath_eval('/hr:Candidate');
					$nodeset = $xpathResult->nodeset;
					$rootIsCandidate = (count($nodeset) > 0);
				} else {
					$xpathContext = new DOMXPath($dom);
					$xpathContext->registerNamespace(hr_ns_prefix, hr_ns_url);
					$nodeset = $xpathContext->query('/hr:Candidate');
					$rootIsCandidate = ($nodeset->length > 0);
				}
				if ($rootIsCandidate) {
					if (version_compare(phpversion(), '5') == -1) { // PHP4
						$node = $nodeset[0];
						$lang = $node->get_attribute("xml:lang");
					} else {
						$node = $nodeset->item(0);
						$lang = $node->getAttribute("xml:lang");
					}
					if (!empty($lang)) {
						include "languages.php";
						if (array_key_exists($lang, $availableLanguageList)) {
							if (move_uploaded_file($tmp_name, $this->dir->filePath($lang, $this->userId)) !== FALSE) {
								$this->dir->setSelectedLanguage($this->userId, $lang);
								$this->setLanguageCode($lang);
								$this->file = $this->dir->getFile($lang, $this->userId);
								return TRUE;
							} else {
								$this->errorMessage = KiteCVTranslate('Could not save the uploaded file.');
							}
						} else {
							$this->errorMessage = KiteCVTranslate('The submitted file was refused because it does not specify a known language.');
						}
					} else {
						$this->errorMessage = KiteCVTranslate('The submitted file was refused because it does not specify a language. Please append attribute xml:lang to the root element ("Candidate").');
					}
				} else {
					$this->errorMessage = KiteCVTranslate('The submitted file was refused because it does not look like an HR-XML Candidate document.');
				}
			} else {
				$this->errorMessage = KiteCVTranslate('Error while parsing the submitted file. Are you sure this is an XML document ?');
			}
		} else {
			$this->errorMessage = KiteCVTranslate('Please specify a file.');
		}
		return FALSE;
	}
	function uploadPhoto() {
		$tmp_name = $_FILES['photoFile']['tmp_name'];
		if (is_uploaded_file($tmp_name)) {
			if (move_uploaded_file($tmp_name, $this->dir->photoPath($this->userId)) !== FALSE) {
				return TRUE;
			} else {
				$this->errorMessage = KiteCVTranslate('Could not save the uploaded file.');
			}
		} else {
			$this->errorMessage = KiteCVTranslate('Please specify a file.');
		}
		return FALSE;
	}
}

// Stolen from DotClear 2
function KiteCVTranslate($str) {
	return (!empty($GLOBALS['_kcv_l10n'][$str])) ? $GLOBALS['_kcv_l10n'][$str] : $str;
}
function getPoFile($file) {
	if (!file_exists($file)) {
		error_log("po file not found '$file'");
		return false;
	}
	$fc = implode('',file($file));
	$res = array();
	$matched = preg_match_all('/(msgid\s+("([^"]|\\\\")*?"\s*)+)\s+'.'(msgstr\s+("([^"]|\\\\")*?(?<!\\\)"\s*)+)/', $fc, $matches);
	if (!$matched) {
		error_log("strings not found in '$file'");
		return false;
	}
	for ($i=0; $i<$matched; $i++) {
		$msgid = preg_replace('/\s*msgid\s*"(.*)"\s*/s','\\1',$matches[1][$i]);
		$msgstr= preg_replace('/\s*msgstr\s*"(.*)"\s*/s','\\1',$matches[4][$i]);
		$msgstr = poString($msgstr);
		if ($msgstr) {
			$res[poString($msgid)] = $msgstr;
		}
	}
	if (!empty($res[''])) {
		$meta = $res[''];
		unset($res['']);
	}
	return $res;
}
function poString($string,$reverse=false) {
	if ($reverse) {
		$smap = array('"', "\n", "\t", "\r");
		$rmap = array('\\"', '\\n"' . "\n" . '"', '\\t', '\\r');
		return trim((string) str_replace($smap, $rmap, $string));
	} else {
		$smap = array('/"\s+"/', '/\\\\n/', '/\\\\r/', '/\\\\t/', '/\\\"/');
		$rmap = array('', "\n", "\r", "\t", '"');
		return trim((string) preg_replace($smap, $rmap, $string));
	}
}
// vim: ts=4 sts=4 sw=4

?>
